package sg4c.protocol;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import sg4c.frontend.command.*;

public class GraphicDescriptionProtocol {

    public static final int CMD_UPDATE_FRAME = 0xee00;
    public final int CMD_END_GRAPHIC = 0x0fe;
    private HashMap<Integer, GraphicsCommand.Factory> commandMapping = new HashMap<Integer, GraphicsCommand.Factory>();

    private final Vector<GraphicsCommand> cmdbuf = new Vector<GraphicsCommand>(1024);

    public GraphicDescriptionProtocol() {
        populateCommandMapping();
    }

    private void populateCommandMapping() {
        commandMapping.put(0xbac01, DrawRect.factory);
        commandMapping.put(0xbac02, DrawEllipse.factory);
        commandMapping.put(0xbac03, DrawLine.factory);
        commandMapping.put(0xbac04, DrawPoint.factory);
        commandMapping.put(0xbac05, DrawPolygon.factory);

        commandMapping.put(0xbac06, Translate.factory);
        commandMapping.put(0xbac07, Rotate.factory);


        commandMapping.put(0xbac08, SetFont.factory);
        commandMapping.put(0xbac09, DrawText.factory);

        commandMapping.put(0xbac0a, SetStrokeWeight.factory);
        commandMapping.put(0xbac0b, SetFillColor.factory);
        commandMapping.put(0xbac0c, SetStrokeColor.factory);
        commandMapping.put(0xbac0d, SetNoFill.factory);

    }

    public GraphicsCommand next(DataInputProtocol in) throws IOException{
        int cmd = in.readInt();
        if( cmd == CMD_END_GRAPHIC ) return null;
        return commandMapping.get(cmd).parse(in);
    }

    public List<GraphicsCommand> parseAll(DataInputProtocol in) throws IOException {
        GraphicsCommand cmd;
        cmdbuf.clear();
        in.next();
        while( (cmd=next(in))!=null ){
            cmdbuf.add(cmd);
        }
        return cmdbuf;
    }

    public void updateFrame(DataOutputProtocol backendOutput) throws IOException {
        backendOutput.writeInt(CMD_UPDATE_FRAME);
        backendOutput.flush();
    }
}
